package com.tsmti.core.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * Title：PimsSystem
 * Class：com.tsmti.core.util.EhcacheUtils
 * Comapny:
 *
 * @author：zcw
 * @version：2.5 CreateTime：2018/1/16 14:57
 * Modify log:
 * Description：
 * 缓存基础类
 */
public class EhcacheUtils extends AbstractObjectSwitchHelper {

	private static CacheManager manager = ((CacheManager) SpringContextUtils.getBean("ehcacheManager"));
	private Cache cache = null;

	public EhcacheUtils() {

	}

	public EhcacheUtils(String cacheName) {
		load(cacheName);
	}

	/**
	 * 加载缓存
	 * 
	 * @param cacheName
	 */
	public void load(String cacheName) {
		cache = manager.getCache(cacheName);
	}

	@Override
	public Object get(String key) {
		if (cache != null) {
			Element element = cache.get(key);
			if (element != null) {
				return element.getObjectValue();
			}
		}
		return null;
	}

	@Override
	public void set(String key, Object value) {
		if (cache != null) {
			cache.put(new Element(key, value));
		}
	}

	@Override
	public boolean remove(String key) {
		if (cache != null) {
			return cache.remove(key);
		}
		return false;
	}
    /**
     * 
     * @title: removeAll   
     * @description: 清楚所有緩存    
     * @return: void
     */
	public void removeAll() {
		if (cache != null) {
			cache.removeAll();
		}
	}

	public static void main(String[] args) {
		String key = "key";
		String value = "1";
		EhcacheUtils ehcacheUtils = new EhcacheUtils("syscommoncache");
		ehcacheUtils.set(key, value);
		ehcacheUtils.remove(key);
		System.out.println(ehcacheUtils.getInt(key));
	}

}